<?php

class Admin_StateController extends Zend_Controller_Action {

    public function init() {
        if (!Zend_Auth::getInstance()->hasIdentity()) {
            $this->_redirect("/admin/login");
        }
        $this->_helper->layout->setLayout("admin");
    }

    public function indexAction() {
        $stateDb = new Admin_Model_State();
        $form = new Admin_Form_StateAdd();
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $stateDb->createNewState(array(
                    'name' => $values['name'],
                ));
            }
        }

        $this->view->allStates = $stateDb->fetchAll();
    }

    public function updateAction() {
        $id = $this->getinputidAction();
        $stateDb = new Admin_Model_State();
        $stateById = $stateDb->getStateById($id);
        $form = new Admin_Form_StateUpdate();
        $form->main($stateById[0]);
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $stateDb->updateState(array(
                    'name' => $values['name']
                        ), $values['id']);
                $this->_redirect("/admin/state/add");
            }
        }
    }

    /**
     * Get State ID.    
     */
    public function getinputidAction() {
        $filters = array(
            'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
        );
        $validators = array(
            'id' => array('Int')
        );
        $input = new Zend_Filter_Input($filters, $validators);
        $input->setData($this->getRequest()->getParams());
        $id = $input->id; //state id
        return $id;
    }

}

